package com.example.douyinserver.collector;

import lombok.AllArgsConstructor;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
//静态资源端口
@RestController
@AllArgsConstructor
public class FileRestController {
    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
    @RequestMapping(value="/static/{name}",method = RequestMethod.GET)
    public void videoPreview(@PathVariable("name") String name,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        //假如我把视频1.mp4放在了static下的video文件夹里面
        //sourcePath 是获取resources文件夹的绝对地址
        //realPath 即是视频所在的磁盘地址
        String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
        String realPath;
        if(name.charAt(name.length()-1)=='4')realPath = sourcePath +"static/video/"+name;
        else realPath = sourcePath +"static/picture/"+name;

        Path filePath = Paths.get(realPath );
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}

